package wetalk.software.bupt.com.wetalk.adapter;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.SpannableString;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import cn.bmob.im.inteface.DownloadListener;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.DownloadManager;
import wetalk.software.bupt.com.wetalk.application.ImageLoadOptions;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.listener.NewRecordPlayClickListener;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.model.po.WeTalkMsg;
import wetalk.software.bupt.com.wetalk.util.FaceTextUtils;
import wetalk.software.bupt.com.wetalk.util.TimeUtil;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.util.WeTalkLog;
import wetalk.software.bupt.com.wetalk.util.WeTalkUtils;
import wetalk.software.bupt.com.wetalk.view.activity.ImageBrowserActivity;
import wetalk.software.bupt.com.wetalk.view.activity.LocationActivity;
import wetalk.software.bupt.com.wetalk.view.activity.UserInfoActivity;
import wetalk.software.bupt.com.wetalk.view.dialog.DialogTips;

/**
 * Created by zhangjie on 2017/12/6.
 */

@SuppressLint("InflateParams")
public class MessageChatAdapter extends BaseListAdapter<WeTalkMsg> {

    //8种Item的类型
    //文本
    private final int TYPE_RECEIVER_TXT = 0;
    private final int TYPE_SEND_TXT = 1;
    //图片
    private final int TYPE_SEND_IMAGE = 2;
    private final int TYPE_RECEIVER_IMAGE = 3;
    //位置
    private final int TYPE_SEND_LOCATION = 4;
    private final int TYPE_RECEIVER_LOCATION = 5;
    //语音
    private final int TYPE_SEND_VOICE = 6;
    private final int TYPE_RECEIVER_VOICE = 7;
    //文件
    private final int TYPE_SEND_FILE = 8;
    private final int TYPE_RECEIVER_FILE = 9;
    private Context mContext;
    String currentObjectId = "";

    DisplayImageOptions options;

    private ImageLoadingListener animateFirstListener = (ImageLoadingListener) new AnimateFirstDisplayListener();

    public MessageChatAdapter(Context context, List<WeTalkMsg> msgList) {
        super(context, msgList);
        //需要获取到当前用户id
        currentObjectId = UserManager.getInstance(context).getCurrentUserObjectId();

        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.ic_launcher)
                .showImageOnFail(R.drawable.ic_launcher)
                .resetViewBeforeLoading(true)
                .cacheOnDisc(true)
                .cacheInMemory(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new FadeInBitmapDisplayer(300))
                .build();
        mContext = context;
    }

    @Override
    public int getItemViewType(int position) {
        WeTalkMsg msg = list.get(position);
        if (msg.getMsgType() == WeTalkConfig.TYPE_IMAGE) {
            return msg.getBelongId().equals(currentObjectId) ? TYPE_SEND_IMAGE : TYPE_RECEIVER_IMAGE;
        } else if (msg.getMsgType() == WeTalkConfig.TYPE_FILE) {
            return msg.getBelongId().equals(currentObjectId) ? TYPE_SEND_FILE : TYPE_RECEIVER_FILE;
        } else if (msg.getMsgType() == WeTalkConfig.TYPE_LOCATION) {
            return msg.getBelongId().equals(currentObjectId) ? TYPE_SEND_LOCATION : TYPE_RECEIVER_LOCATION;
        } else if (msg.getMsgType() == WeTalkConfig.TYPE_VOICE) {
            return msg.getBelongId().equals(currentObjectId) ? TYPE_SEND_VOICE : TYPE_RECEIVER_VOICE;
        } else {
            return msg.getBelongId().equals(currentObjectId) ? TYPE_SEND_TXT : TYPE_RECEIVER_TXT;
        }
    }

    @Override
    public int getViewTypeCount() {
        return 10;
    }

    private View createViewByType(WeTalkMsg message, int position) {
        int type = message.getMsgType();
        if (type == WeTalkConfig.TYPE_IMAGE) {//图片类型
            return getItemViewType(position) == TYPE_RECEIVER_IMAGE ?
                    mInflater.inflate(R.layout.item_chat_received_image, null)
                    :
                    mInflater.inflate(R.layout.item_chat_sent_image, null);
        } else if (type == WeTalkConfig.TYPE_FILE) {//文件类型
            return getItemViewType(position) == TYPE_RECEIVER_FILE ?
                    mInflater.inflate(R.layout.item_chat_received_file, null)
                    :
                    mInflater.inflate(R.layout.item_chat_sent_file, null);
        } else if (type == WeTalkConfig.TYPE_LOCATION) {//位置类型
            return getItemViewType(position) == TYPE_RECEIVER_LOCATION ?
                    mInflater.inflate(R.layout.item_chat_received_location, null)
                    :
                    mInflater.inflate(R.layout.item_chat_sent_location, null);
        } else if (type == WeTalkConfig.TYPE_VOICE) {//语音类型
            return getItemViewType(position) == TYPE_RECEIVER_VOICE ?
                    mInflater.inflate(R.layout.item_chat_received_voice, null)
                    :
                    mInflater.inflate(R.layout.item_chat_sent_voice, null);
        } else {//剩下默认的都是文本
            return getItemViewType(position) == TYPE_RECEIVER_TXT ?
                    mInflater.inflate(R.layout.item_chat_received_message, null)
                    :
                    mInflater.inflate(R.layout.item_chat_sent_message, null);
        }
    }

    @Override
    public View bindView(final int position, View convertView, ViewGroup parent) {
        final WeTalkMsg item = list.get(position);
        if (convertView == null) {
            convertView = createViewByType(item, position);
        }
        ImageView iv_avatar = ViewHolder.get(convertView, R.id.iv_avatar);
        TextView tv_time = ViewHolder.get(convertView, R.id.tv_time);
        //文本类型
        final ImageView iv_fail_resend = ViewHolder.get(convertView, R.id.iv_fail_resend);//失败重发
        final TextView tv_send_status = ViewHolder.get(convertView, R.id.tv_send_status);//发送状态
        final TextView tv_message = ViewHolder.get(convertView, R.id.tv_message);
        final ProgressBar progress_load = ViewHolder.get(convertView, R.id.progress_load);//进度条
        //图片
        ImageView iv_picture = ViewHolder.get(convertView, R.id.iv_picture);
        //位置
        TextView tv_location = ViewHolder.get(convertView, R.id.tv_location);
        //语音
        final ImageView iv_voice = ViewHolder.get(convertView, R.id.iv_voice);
        //语音长度
        final TextView tv_voice_length = ViewHolder.get(convertView, R.id.tv_voice_length);
        TextView file_name = ViewHolder.get(convertView, R.id.msg_file_name);
        if (file_name != null) file_name.setMovementMethod(ScrollingMovementMethod.getInstance());
        TextView file_size = ViewHolder.get(convertView, R.id.msg_file_size);
        LinearLayout file_msg = ViewHolder.get(convertView, R.id.file_msg);

        tv_time.setVisibility(View.GONE);
        //点击头像进入个人资料
        String avatar = item.getBelongAvatar();
        if (avatar != null && !avatar.equals("")) {//加载头像-为了不每次都加载头像
            ImageLoader.getInstance().displayImage(avatar, iv_avatar, ImageLoadOptions.getOptions(), animateFirstListener);
        } else {
            iv_avatar.setImageResource(R.drawable.head);
        }
        if (tv_message != null) {
            tv_message.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    final String chooseMsg = tv_message.getText().toString();
                    DialogTips dialog = new DialogTips(mContext, chooseMsg, "复制", "撤回", true, true);
                    // 设置成功事件
                    dialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialogInterface, int userId) {
                            dialogInterface.dismiss();
                            //实现复制功能
                            ClipboardManager cmb = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                            cmb.setText(chooseMsg);
                            ShowToast("已复制到粘贴板");
                        }
                    });
                    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialogInterface) {
                            dialogInterface.dismiss();
                            //TODO:实现撤回功能
                        }
                    });
                    // 显示确认对话框
                    dialog.show();
                    dialog = null;
                    return false;
                }
            });
        }

        iv_avatar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(mContext, UserInfoActivity.class);
                if (getItemViewType(position) == TYPE_RECEIVER_TXT
                        || getItemViewType(position) == TYPE_RECEIVER_IMAGE
                        || getItemViewType(position) == TYPE_RECEIVER_LOCATION
                        || getItemViewType(position) == TYPE_RECEIVER_VOICE
                        || getItemViewType(position) == TYPE_RECEIVER_FILE) {
                    User user = new User(item.getBelongId(), item.getBelongUsername(), "", item.getBelongAvatar(), "", "", "");
                    intent.putExtra("from", "other");
                    intent.putExtra("action", "look");
                    intent.putExtra("username", item.getBelongUsername());
                    intent.putExtra("user", user);
                    mContext.startActivity(intent);
                } else {
                    Toast.makeText(mContext, "请不要点击自己", Toast.LENGTH_LONG).show();
                }
            }
        });

        if (position > 0) {
            WeTalkMsg tmp = list.get(position - 1);
            Date priTime = new Date(Long.parseLong(tmp.getMsgTime()) * 1000);
            Date nowTime = new Date(Long.parseLong(item.getMsgTime()) * 1000);
            SimpleDateFormat msdf = new SimpleDateFormat("mm");
            long t = (long) (Float.parseFloat(msdf.format(nowTime)) - Float.parseFloat(msdf.format(priTime)));

            //间隔1分钟的显示一次
            if (t >= 1) {
                tv_time.setVisibility(View.VISIBLE);
                tv_time.setText(TimeUtil.getChatTime(Long.parseLong(item.getMsgTime())));
            }
        }

        if (getItemViewType(position) == TYPE_SEND_TXT
//				||getItemViewType(position)==TYPE_SEND_IMAGE//图片单独处理
                || getItemViewType(position) == TYPE_SEND_LOCATION
                || getItemViewType(position) == TYPE_SEND_VOICE) {//只有自己发送的消息才有重发机制

            // 状态描述
            if (item.getStatus() == WeTalkConfig.STATUS_SEND_SUCCESS) {//发送成功
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                if (item.getMsgType() == WeTalkConfig.TYPE_VOICE) {
                    tv_send_status.setVisibility(View.GONE);
                    tv_voice_length.setVisibility(View.VISIBLE);
                } else {
                    tv_send_status.setVisibility(View.VISIBLE);
                    tv_send_status.setText("已发送");
                }
            } else if (item.getStatus() == WeTalkConfig.STATUS_SEND_FAIL) {//服务器无响应或者查询失败等原因造成的发送失败，均需要重发
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.VISIBLE);
                tv_send_status.setVisibility(View.INVISIBLE);
                if (item.getMsgType() == WeTalkConfig.TYPE_VOICE) {
                    tv_voice_length.setVisibility(View.GONE);
                }
            } else if (item.getStatus() == WeTalkConfig.STATUS_SEND_RECEIVERED) {//对方已接收到
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                if (item.getMsgType() == WeTalkConfig.TYPE_VOICE) {
                    tv_send_status.setVisibility(View.GONE);
                    tv_voice_length.setVisibility(View.VISIBLE);
                } else {
                    tv_send_status.setVisibility(View.VISIBLE);
                    tv_send_status.setText("已阅读");
                }
            } else if (item.getStatus() == WeTalkConfig.STATUS_SEND_START) {//开始上传
                progress_load.setVisibility(View.VISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                tv_send_status.setVisibility(View.INVISIBLE);
                if (item.getMsgType() == WeTalkConfig.TYPE_VOICE) {
                    tv_voice_length.setVisibility(View.GONE);
                }
            }
        }
        //根据类型显示内容
        final String text = item.getContent();
        switch (item.getMsgType()) {
            case WeTalkConfig.TYPE_TEXT:
                try {
                    SpannableString spannableString = FaceTextUtils
                            .toSpannableString(mContext, text);
                    tv_message.setText(spannableString);
                } catch (Exception e) {
                    WeTalkLog.e("MessageChatAdapter", "" + e);
                }
                break;

            case WeTalkConfig.TYPE_IMAGE://图片类
                try {
                    if (text != null && !text.equals("")) {//发送成功之后存储的图片类型的content和接收到的是不一样的
                        dealWithImage(position, progress_load, iv_fail_resend, tv_send_status, iv_picture, item);
                    }
                    iv_picture.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            Intent intent = new Intent(mContext, ImageBrowserActivity.class);
                            ArrayList<String> photos = new ArrayList<>();
                            photos.add(getImageUrl(item));
                            intent.putStringArrayListExtra("photos", photos);
                            intent.putExtra("position", 0);
                            mContext.startActivity(intent);
                        }
                    });

                } catch (Exception e) {
                    WeTalkLog.e("MessageChatAdapter", "" + e);
                }
                break;
            case WeTalkConfig.TYPE_VOICE://语音消息
                try {
                    if (text != null && !text.equals("")) {
                        tv_voice_length.setVisibility(View.VISIBLE);
                        String content = item.getContent();
                        if (item.getBelongId().equals(currentObjectId)) {//发送的消息
                            if (item.getStatus() == WeTalkConfig.STATUS_SEND_RECEIVERED
                                    || item.getStatus() == WeTalkConfig.STATUS_SEND_SUCCESS) {//当发送成功或者发送已阅读的时候，则显示语音长度
                                tv_voice_length.setVisibility(View.VISIBLE);
                                progress_load.setVisibility(View.GONE);
                                String length = content.split("&")[2];
                                tv_voice_length.setText(length + "\''");
                            } else {
                                progress_load.setVisibility(View.GONE);
                                tv_voice_length.setVisibility(View.VISIBLE);
                                String length = content.split("&")[1];
                                int l = Integer.parseInt(length);
                                length += "\''";
                                for (int i = 0; i < l; i++) {
                                    length += "   ";
                                }
                                SpannableString spannableString = FaceTextUtils
                                        .toSpannableString(mContext, length);
                                tv_voice_length.setText(spannableString);
                            }
                        } else {//收到的消息
                            //收到的应该是url，下载下来
                            tv_voice_length.setVisibility(View.VISIBLE);
                            boolean isExists = DownloadManager.checkTargetPathExist(currentObjectId, item);

                            if (!isExists) {//若指定格式的录音文件不存在，则需要下载，因为其文件比较小，故放在此下载
                                final String length = "3\'      ";
                                DownloadManager downloadTask = new DownloadManager(mContext, item, new DownloadListener() {
                                    @Override
                                    public void onStart() {
                                        progress_load.setVisibility(View.VISIBLE);
                                        tv_voice_length.setVisibility(View.GONE);
                                        iv_voice.setVisibility(View.INVISIBLE);//只有下载完成才显示播放的按钮
                                    }

                                    @Override
                                    public void onSuccess() {
                                        progress_load.setVisibility(View.GONE);
                                        tv_voice_length.setVisibility(View.VISIBLE);
                                        SpannableString spannableString = FaceTextUtils
                                                .toSpannableString(mContext, length);
                                        tv_voice_length.setText(spannableString);
                                        iv_voice.setVisibility(View.VISIBLE);
                                        //item = WeTalkDB.create(mContext).getMessage(item.getConversationId(), item.getMsgTime());
                                    }

                                    @Override
                                    public void onError(String error) {
                                        progress_load.setVisibility(View.GONE);
                                        tv_voice_length.setVisibility(View.GONE);
                                        iv_voice.setVisibility(View.INVISIBLE);
                                    }
                                });
                                downloadTask.execute(content);
                            } else {
                                String length = "3\'       ";
                                SpannableString spannableString = FaceTextUtils
                                        .toSpannableString(mContext, length);
                                tv_voice_length.setText(spannableString);
                            }
                        }
                    }
                    //播放语音文件
                    iv_voice.setOnClickListener(new NewRecordPlayClickListener(mContext, item, iv_voice));
                } catch (Exception e) {
                    WeTalkLog.e("MessageChatAdapter", "" + e);
                }
                break;
            case WeTalkConfig.TYPE_FILE:
                if (text != null && !text.equals("")) {
                    String[] tmp = text.split("/");
                    String fileName = tmp[tmp.length - 1];
                    file_name.setText(fileName);
                    if (item.getBelongId().equals(currentObjectId)) {//发送的消息
                        if (item.getStatus() == WeTalkConfig.STATUS_SEND_RECEIVERED
                                || item.getStatus() == WeTalkConfig.STATUS_SEND_SUCCESS) {
                            progress_load.setVisibility(View.INVISIBLE);
                            iv_fail_resend.setVisibility(View.INVISIBLE);
                            tv_send_status.setVisibility(View.VISIBLE);
                            tv_send_status.setText("已发送");
                        }else {
                            progress_load.setVisibility(View.GONE);
                            iv_fail_resend.setVisibility(View.VISIBLE);
                        }
                    } else {//收到的消息
                        boolean isExists = DownloadManager.checkTargetPathExist(currentObjectId, item);
                        if (!isExists) {//若文件不存在，则需要下载，因为其文件比较小，故放在此下载
                            DownloadManager downloadTask = new DownloadManager(mContext, item, new DownloadListener() {
                                @Override
                                public void onStart() {
                                    progress_load.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onSuccess() {
                                    progress_load.setVisibility(View.GONE);
                                    iv_fail_resend.setVisibility(View.INVISIBLE);
                                    notifyDataSetChanged();
                                }

                                @Override
                                public void onError(String error) {
                                    progress_load.setVisibility(View.GONE);
                                    iv_fail_resend.setVisibility(View.VISIBLE);
                                }
                            });
                            downloadTask.execute(text);
                        } else {
                            progress_load.setVisibility(View.GONE);

                        }
                    }
                }
                file_msg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String content = list.get(position).getContent();
                        String filePath = "";
                        if (content.contains("&")) {
                            filePath = content.split("&")[0];
                        } else {
                            filePath = content.substring(8);
                        }

                        Intent intent = WeTalkUtils.openFile(filePath);
                        if (intent != null) mContext.startActivity(intent);
                    }
                });
                break;
            default:
                break;
        }
        return convertView;
    }

    /**
     * 获取图片的地址--
     *
     * @param @param  item
     * @param @return
     * @return String
     * @throws
     * @Description: TODO
     */
    private String getImageUrl(WeTalkMsg item) {
        String showUrl = "";
        String text = item.getContent();
        if (item.getBelongId().equals(currentObjectId)) {//
            if (text.contains("&")) {
                showUrl = text.split("&")[0];
            } else {
                showUrl = text;
            }
        } else {//如果是收到的消息，则需要从网络下载
            showUrl = text;
        }
        return showUrl;
    }

    /**
     * 处理图片
     */
    private void dealWithImage(int position, final ProgressBar progress_load, ImageView iv_fail_resend, TextView tv_send_status, ImageView iv_picture, WeTalkMsg item) {
        String text = item.getContent();
        if (getItemViewType(position) == TYPE_SEND_IMAGE) {//发送的消息
            Log.i("smile", position + ",状态：" + item.getStatus());
            if (item.getStatus() == WeTalkConfig.STATUS_SEND_START) {
                progress_load.setVisibility(View.VISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                tv_send_status.setVisibility(View.INVISIBLE);
            } else if (item.getStatus() == WeTalkConfig.STATUS_SEND_SUCCESS) {
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                tv_send_status.setVisibility(View.VISIBLE);
                tv_send_status.setText("已发送");
            } else if (item.getStatus() == WeTalkConfig.STATUS_SEND_FAIL) {
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.VISIBLE);
                tv_send_status.setVisibility(View.INVISIBLE);
            } else if (item.getStatus() == WeTalkConfig.STATUS_SEND_RECEIVERED) {
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                tv_send_status.setVisibility(View.VISIBLE);
                tv_send_status.setText("已阅读");
            }
//			如果是发送的图片的话，因为开始发送存储的地址是本地地址，发送成功之后存储的是本地地址+"&"+网络地址，因此需要判断下
            String showUrl = "";
            if (text.contains("&")) {
                showUrl = text.split("&")[0];
            } else {
                showUrl = text;
            }
            //为了方便每次都是取本地图片显示
            WeTalkUtils.initImageLoader(mContext);
            ImageLoader.getInstance().displayImage(showUrl, iv_picture);
        } else {
            WeTalkUtils.initImageLoader(mContext);
            //text="file://"+text;
            ImageLoader.getInstance().displayImage(text, iv_picture, options, new ImageLoadingListener() {

                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    progress_load.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, com.nostra13.universalimageloader.core.assist.FailReason failReason) {
                    progress_load.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    progress_load.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {
                    progress_load.setVisibility(View.INVISIBLE);
                }
            });
        }
    }

    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

}
